// const observer = new Observer()
function Observer() {
  // 存储key和回调
  this.events = {}; // {牛奶: [fn,fn,fn]}
}

Observer.prototype.subscribe = function (key, fn) {
  // 牛奶  ()=>{}
  this.events[key] ? this.events[key].push(fn) : (this.events[key] = [fn]);// {'牛奶':[fn,fn,fn],'西瓜妹妹':[fn]}
};
Observer.prototype.emit = function (key) {
  // 找到 key 为牛奶的回调
  this.events[key] && this.events[key].forEach((fn) => fn());
};

const observer = new Observer()
// 订阅
observer.subscribe("牛奶", () => {
  console.log("牛奶来啦");
});
observer.subscribe("牛奶", () => {
  console.log("牛奶来啦");
});
observer.subscribe("牛奶", () => {
  console.log("牛奶来啦");
});
observer.subscribe("西瓜妹妹", () => {
  console.log("西瓜妹妹来嫁给你辣");
});
observer.emit("牛奶"); // 往这个箱子里放牛奶
